<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Taobao\top\TopClient;
use App\Http\Controllers\Taobao\top\request\TbkItemGetRequest;

class UserRegController extends Controller{
    //首页
    public function index(){
        print_r("12313213");exit();
    }

    //发送短信
    public function sendSms(){
        $param = request()->all();
        $messages = ['mobile.regex'=>'手机号不合法'];
        $validator = \Validator::make($param, [
            'mobile' => 'required|unique:investor',
            'mobile' => 'regex:/^1[345789][0-9]{9}$/',     //正则验证
        ], $messages);
        $error = $validator->errors()->first();
        if ($error) appMessage(1,$error);

        $res = sendToSms($param["mobile"]);
        $res ? appMessage(0,"短信发送成功") :  appMessage(1,"短信发送失败");
    }

    /**
     * 手机自动注册登录
     * @param mobile手机号 code验证码
     */
    public function login(){
        $param = request()->all();
        $messages = ['mobile.regex'=>'手机号不合法'];
        $validator = \Validator::make($param, [
            'mobile' => 'required|unique:investor',
            'mobile' => 'regex:/^1[345789][0-9]{9}$/',     //正则验证
            'code'   => 'required'
        ], $messages);
        $error = $validator->errors()->first();
        if ($error) appMessage(1,$error);
       try{
           $where = ["mobile"=>$param["mobile"],"code"=>$param["code"],"status"=>1];
           $res = DB::table("send_sms")->where($where)->orderBy('id','desc')->first();
           if ($res){
               if ($res->addtime+600<time()){
                   appMessage(1,"验证码已过期");
               }else{
                   $today = date("Y-m-d H:i:s");
                   //$userInfo = DB::table("members")->where("phone",$param["mobile"])->orderBy('id','desc')->first();
                   //$userInfo = json_decode(json_encode($userInfo), true);
                   $userInfo=\App\Models\Member::query()
                       ->where("phone",$param["mobile"])
                       ->select('id','phone','avatar','uuid')
                       ->first();
                   if (empty($userInfo)){
                       $userInfo = ["phone"=>$param["mobile"],'password'=>bcrypt("123456"),'uuid'=>\Faker\Provider\Uuid::uuid(),"created_at"=>$today,"updated_at"=>$today,"avatar"=>""];
                       $userInfo['id'] = DB::table("members")->insertGetId($userInfo);
                   }else{
                       $userInfo=$userInfo->toArray();
                   }
                   $token = generate_user_token($userInfo,"loginToken");
                   if ($token){
                       DB::table("send_sms")->where('id',$res->id)->update(["status"=>2]);
                       appMessage(0,"登陆成功",["userId"=>$userInfo["id"],"token"=>$token,"avatar"=>$userInfo['avatar']]);
                   }else{
                       appMessage(1,"token生成失败，请重新登录");
                   }
               }
           }else{
               appMessage(1,"验证码错误或已使用");
           }
       }catch (\Exception $e){
           appMessage(1,$e->getMessage());
       }
    }

    /**
     * 获得首页分类
     */
    public function cate(){
        $where = ["pid"=>0,"level"=>1,"status"=>1];
        $list = DB::table("category")->where($where)->orderBy('sort','desc')->take(5)->get();
        $list = json_decode(json_encode($list), true);
        $default = "/images/default.jpg";
        foreach ($list as $key=>$item){
            $list[$key]['img'] = $item["img"] ? $item["img"] : $default;
        }
        appMessage(0,"登陆成功",$list);
    }

    /**
     * @param name搜索名称
     * 获得淘宝账号
     */
    public function searchGoods(){
        $param = request()->all();
        $validator = \Validator::make($param, [     //正则验证
            'name'   => 'required'
        ]);
        $page = empty($param["page"]) ? 1 : $param["page"];
        $pageSize = empty($param["pageSize"]) ? 20 : $param["pageSize"];
        $error = $validator->errors()->first();
        if ($error) appMessage(1,$error);
        $url = "http://tkapi.apptimes.cn/search?appkey=".getenv('TKAPI_APP_KEY')."&appsecret=".getenv('TKAPI_APP_SECRET')."&";
        $reqData = [
            'q' => $param['name'],
            'page'=>$page,
            'pagesize'=>$pageSize
        ];
        $type = empty($param['type']) ? 'other' : $param['type'];
        $sort = empty($param['sort']) ? 'asc' : $param['sort'];
        switch ($type){
            case 'sales':
                $reqData['sort'] = $type.":".$sort;
                break;
            case 'tkrate':
                $reqData['sort'] = $type.":".$sort;
                break;
            case 'price':
                $reqData['sort'] = $type.":".$sort;
                break;
            default:
                break;
        }
        $reqParam = http_build_query($reqData);
        $url .= $reqParam;
        $res = curl_request($url);// file_get_contents
        $res = json_decode($res,true);
        if (empty($res['errcode'])){
            $list = $res['data']['result_list'];
            appMessage(0,"搜索成功",$list);
        }else{
            appMessage(1,'查询失败');
        }
    }
}